<template>
  <div class="purchase-root">
    <el-card shadow="never" body-style="padding: 20px 20px 0px 20px;">
      <el-form
        ref="form"
        :rules="$rules.warehouseExRules"
        inline
        :model="form"
        class="form-options"
        label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="出库单号" prop="outNo">
              <el-input v-model="form.outNo" disabled/>
            </el-form-item>
            <el-form-item label="出库仓库" prop="warehouseId">
              <el-select
                v-model="form.warehouseId"
                clearable
                filterable
                @change="onWarehouseChange"
                placeholder="请选择仓库"
                :disabled="(form.busOutDetailsList&&form.busOutDetailsList.length>0)||type!=2 ">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="出库说明" class="long-content">
              <el-input
                type="textarea"
                :rows="2"
                :disabled="type!=2"
                placeholder="请输入说明"
                v-model="form.outExplain">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标位置" prop="targetLocation">
              <el-select
                v-model="form.targetLocation"
                clearable
                filterable
                placeholder="请选择目标位置"
                :disabled="type!=2">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="出库完成时间">
              <el-input
                v-model="form.outTime"
                disabled/>
            </el-form-item>

            <el-form-item label="最近操作人" v-if="form.id">
              <el-input v-model="form.operName" disabled/>
            </el-form-item>
            <el-form-item label="最近操作时间" v-if="form.id">
              <el-input
                v-model="form.operTime"
                disabled/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div>
      <EquipmentEx
        v-for="(item, index) in form.busOutDetailsList"
        ref="EquipmentEx"
        :form="item"
        :warehouseId="selectWarehouseId"
        :type="type==0?0:1"
        :equipment-data-extra="item.baseEquipmentDetails"
        @onDelete="onEquipmentDelete(index)"
        :treeData="equipmentTreeData"
        :key="index"/>
    </div>
  </div>
</template>

<script>
import EquipmentEx from '../EquipmentEx'
import { getUserCondition } from '@/api/common'
import { addWarehouseEx } from '@/api/warehouse'
import {
  getBaseEquipmentType, getWarehouse
} from '@/api/warehouse'
import { setTreeDisable } from '@/utils/public'

export default {
  name: 'WarehouseExComponent',
  components: {
    EquipmentEx
  },
  props: {
    // 0:只读 1：修改  2：新增
    type: {
      type: Number,
      default: 0
    },
    form: {
      type: Object,
      default: function() {
        return {
          id: '',
          operName: '',
          outExplain: '',
          status: '',
          warehouseId: '',
          outTime: '',
          operId: '',
          operTime: '',
          outNo: '',
          targetLocation: '',
          busOutDetailsList: []
        }
      }
    }
  },
  data() {
    return {
      purchaserLoading: false,
      purchaserOptions: [],
      equipments: [{}, {}, {}, {}],
      equipmentTreeData: [],
      selectWarehouseId: '',
      warehouseOptions: []
    }
  },
  mounted() {
    getBaseEquipmentType({}).then(res => {
      this.equipmentTreeData = res.resultData
    })
    getWarehouse({}).then(res => {
      this.warehouseOptions = res.resultData
    })
    this.selectWarehouseId = this.form.warehouseId + ''
  },
  methods: {
    handleSelectEquipmentList() {
      getBaseEquipmentType({}).then(res => {
        this.equipmentTreeData = res.resultData
        this.form.busOutDetailsList.forEach(res => {
          if (res.equipmentTypeId) {
            const id = res.equipmentTypeId[res.equipmentTypeId.length - 1]
            setTreeDisable(id, this.equipmentTreeData, true)
          }
        })
        // console.log(this.equipmentTreeData)
      })
    },
    addEquipment() {
      this.validEquipmentData().then(res => {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const data = {
              id: '',
              equipmentTypeId: '',
              expirationDate: '',
              outStockNum: '',
              outNum: 0,
              productionDate: '',
              shelfLife: ''
            }
            this.form.busOutDetailsList.push(data)
          } else {
            return false
          }
        })
      })
    },
    onWarehouseChange(event) {
      this.selectWarehouseId = event + ''
    },
    async validEquipmentData() {
      const equipmentP = []
      for (let i = 0; i < this.form.busOutDetailsList.length; i++) {
        equipmentP.push(this.$refs['EquipmentEx'][i].validData())
      }
      if (equipmentP.length > 0) {
        return Promise.all(equipmentP)
      } else {
        return new Promise(resolve => resolve())
      }
    },
    saveAndSubmit() {
      this.validEquipmentData().then(res => {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            // 保存
            const param = { status: 1 }
            Object.assign(param, this.form)
            param.status = 1
            param.busOutDetailsList.forEach(item => {
              const lastIndex = item.equipmentTypeId.length - 1
              item.equipmentTypeId = item.equipmentTypeId[lastIndex]
            })
            addWarehouseEx(param).then(response => {
              this.$message({
                message: '保存提交成功',
                type: 'success'
              })
              this.$emit('onSubmit', {})
            })
          } else {
            return false
          }
        })
      })
    },
    onEquipmentDelete(index) {
      this.form.busOutDetailsList.splice(index, index + 1)
    },
    save() {
      this.validEquipmentData().then(res => {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const param = { status: 0 }
            Object.assign(param, this.form)
            param.status = 0
            param.busOutDetailsList.forEach(item => {
              const lastIndex = item.equipmentTypeId.length - 1
              item.equipmentTypeId = item.equipmentTypeId[lastIndex]
            })
            // 保存
            addWarehouseEx(param).then(response => {
              this.$message({
                message: '保存成功',
                type: 'success'
              })
              this.$emit('onSave', {})
            })
          } else {
            return false
          }
        })
      })
    },
    /**
     * 模糊查询采购单号
     * @param queryString
     * @param cb
     */
    querySearchOrderNum: function(queryString, cb) {
      // 调用 callback 返回建议列表的数据
      const results = []
      cb(results)
    },
    /**
     * 选择采购单号
     * @param item
     */
    handleSelectOrderNum(item) {
      // console.log(item)
    },
    /**
     * 模糊查询采购人
     * @param queryString
     * @param cb
     */
    querySearchPurchaser: function(queryString) {
      // 调用 queryString 返回建议列表的数据
      // 使用动态 el-option 来加载
      this.purchaserLoading = true
      getUserCondition({ userName: queryString, page: 1, rows: 20 }).then(res => {
        this.purchaserLoading = false
        this.purchaserOptions = res.resultData
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.purchase-root {
  max-height: 680px;
  overflow-y: auto;

  ::v-deep .el-form-item__content {
    width: 185px !important;

    .el-date-editor.el-input, .el-date-editor.el-input__inner {
      width: 100%;
    }
  }

  ::v-deep .long-content {
    .el-form-item__content {
      width: 480px !important;

      .el-date-editor--datetimerange.el-input, .el-date-editor--datetimerange.el-input__inner {
        width: 100%;
      }

      .el-date-editor--daterange.el-input, .el-date-editor--daterange.el-input__inner, .el-date-editor--timerange.el-input, .el-date-editor--timerange.el-input__inner {
        width: 100%;
      }

      .el-cascader--small {
        width: 100%;
      }
    }
  }
}
</style>
